package com.muyi.controller.account;

import com.alibaba.fastjson.JSON;
import com.muyi.pojo.entity.Account;
import com.muyi.service.UserService;
import com.muyi.service.impl.UserServiceImpl;
import com.muyi.util.MD5Util;
import com.muyi.pojo.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

@MultipartConfig //注解让servlet具有上传功能
@WebServlet(name = "ServletRegister", value = "/register")
public class ServletRegister extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取请求参数
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        //获取头像文件
        Part headImg = request.getPart("headImg");
        //获取文件名称
        String fileName = headImg.getSubmittedFileName();
        //在文件名前面加上uuid，避免文件冲突
        String uuid = UUID.randomUUID().toString().replace("-", "");
        fileName = uuid + fileName;
        //将头像上传到服务器
        String url = request.getServletContext().getRealPath("/") + "/" + fileName;
        headImg.write(url);

        //对密码进行md5加密
        String s1 = MD5Util.getMD5String(pwd);
        String pwdJM = MD5Util.getMD5String(s1 + MD5Util.SALT);

        //将注册的数据添加到account表
        Account account = new Account();
        account.setUsername(username);
        account.setPwd(pwdJM);
        account.setImg_url(request.getContextPath() + "/" + fileName);
        Result result = null;
        try {
            result = userService.register(account);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将执行结果返回前端
        response.getWriter().write(JSON.toJSONString(result));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
